function [m, ge] = meannoinfnan(x, dim)
% meannoinfnan  - build mean of elements other than Inf/NaN
%
% FORMAT:       [m, ge] = meannoinfnan(x [, dim])
%
% Input fields:
%
%       x           data
%       dim         optional dimension, default: 1st non-singleton
%
% Output fields:
%
%       m           mean over dim (if all elements Inf/NaN := 0)
%       ge          good entries in x

% Version:  v0.7g
% Build:    9040116
% Date:     Apr-01 2009, 4:27 PM CEST
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin < 1 || ...
   ~isnumeric(x)
    error( ...
        'BVQXtools:BadArgument', ...
        'Bad or missing first argument.' ...
    );
end
if ~isa(x, 'double')
    x = double(x);
end
if nargin < 2 || ...
   ~isa(dim, 'double') || ...
    numel(dim) ~= 1 || ...
    isinf(dim) || ...
    isnan(dim) || ...
    dim < 1 || ...
    dim > ndims(x)
    dim = findfirst(size(x) > 1);
    if isempty(dim)
        dim = 1;
    end
end

% build sum of good elements
ge = (~isinf(x) & ~isnan(x));
x(~ge) = 0;
m = sum(ge .* x, dim) ./ sum(ge, dim, 'double');
m(isnan(m)) = 0;
